﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Security.Cryptography;


namespace FrbaBus.Login
{
    public partial class FormLogin : Form
    {

        public int logon = 0;

        public FormLogin()
        {
            InitializeComponent();
            this.tbUser.Focus();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            this.Hide();
            //Application.Exit();
            
        }
        private static string GetSHA256(string text)
            {

                SHA256 sha256 = SHA256.Create();

                byte[] hashValue = sha256.ComputeHash(Encoding.UTF8.GetBytes(text));

                string hex = "";

                foreach (byte x in hashValue)
                {
                    hex += String.Format("{0:x2}", x);
                }
                return hex;

            }



        private void btnAcep_Click(object sender, EventArgs e)
        {
            if ((tbUser.Text.Trim() != string.Empty))
            {

                string hashString;
                string hashBD;

                hashString = GetSHA256(tbPass.Text.Trim());

                string query;

                query = "SELECT usu_habilitado AS Habil, adm_password AS Pass, US.usu_codigo AS usuarioId " +
                         "FROM THE_BEST_IAS.administradores AD " +
                         "JOIN THE_BEST_IAS.usuarios US ON US.usu_codigo=AD.usu_codigo " +
                         "WHERE UPPER(adm_username) = '" + this.tbUser.Text.Trim().ToUpperInvariant() + "'";


                SqlDataReader dr = DbHelper.ExecuteQuery(query);

                if (dr.HasRows)
                {
                    string habilitado = "";

                    while (dr.Read())
                    {
                        habilitado = dr["Habil"].ToString();

                        if (dr["Pass"].ToString().Length != 0)
                            hashBD = dr["Pass"].ToString();
                        else
                            hashBD = "";

                        if (habilitado == "False")
                        {
                            MessageBox.Show("El Usuario se encuentra inhabilitado.", "Informacion");
                            logon = 0;
                            tbPass.Text = "";
                            tbUser.Focus();
                        }
                        else
                        {
                            if (hashBD == hashString)
                                if (logon == 2)
                                {
                                    MessageBox.Show("No se puede ingresar a la aplicacion. Tercer intento de logueo", "Informacion");
                                    Inhabilitar_User();
                                    Application.Exit();
                                }

                                else
                                {
                                    //Entro correctamente en la aplicacion!

                                    UsuarioLogueado.userName = tbUser.Text;
                                    UsuarioLogueado.userId = long.Parse(dr["usuarioId"].ToString());
                                    // long.Parse(r[LONGDATAPOSITION].ToString())
                                    logon = 0;
                                    this.Hide();
                                    
                                    FormLogueado form = new FormLogueado();
                                    form.ShowDialog(this);

                                    // Ver los ".visible" de cada elemento con un query
                                }
                            else
                            {
                                if (logon != 2)
                                {
                                    this.tbPass.Text = "";
                                    logon++;
                                    MessageBox.Show("Error en la Password", "Informacion");
                                    tbPass.Focus();
                                }
                                else
                                {
                                    MessageBox.Show("No se puede ingresar a la aplicacion. Tercer intento de logueo", "Informacion");
                                    Inhabilitar_User();
                                    this.Hide();
                                    Application.Exit();
                                }

                            }
                        }
                    }
                }
                else
                {
                    if (logon != 2)
                    {
                        MessageBox.Show("Los datos ingresados no son correctos. Por favor, intentelo nuevamente", "Informacion");
                        logon++;
                    }
                    else
                    {
                        MessageBox.Show("No se puede ingresar a la aplicacion. Tercer intento de logueo, su usuario seria inhabilitado", "Informacion");
                        Inhabilitar_User();
                        this.Hide();
                        //Application.Exit();
                    }
                }
            }
            else
            {
                MessageBox.Show("Los 2 campos son obligatorios", "Informacion");
            }


        }

        private void FormLogin_FormClosed(object sender, FormClosedEventArgs e)
        {
            this.Hide();
            Application.Exit();
        }

        private void Inhabilitar_User()
        {
            string query = "";

            query = "UPDATE THE_BEST_IAS.usuarios SET usu_habilitado = 0 " ;
            query += "FROM THE_BEST_IAS.usuarios US ";
            query += "INNER JOIN THE_BEST_IAS.administradores AD ON AD.usu_codigo=US.usu_codigo ";
            query += " WHERE UPPER(adm_username) = '" + tbUser.Text.ToUpperInvariant().Trim() + "'";

            DbHelper.ExecuteNonQuery(query);

            MessageBox.Show("El usuario: " + tbUser.Text.Trim() + " ha sido bloqueado", "Error");

            this.tbPass.Text = "";
        }

        private void tbPass_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)13)
            {
                this.btnAcep_Click(sender, e);
            }

            if (e.KeyChar == (char)39)
            {
                e.Handled = true;
            }

        }

        private void tbUser_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)39)
            {
                e.Handled = true;
            }
        }

        private void FormLogin_Load(object sender, EventArgs e)
        {

        }

        private void tbUser_TextChanged(object sender, EventArgs e)
        {

        }

        private void tbPass_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
